package net;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.concurrent.Executors;

import net.code.CodecFactory;

import org.apache.log4j.Logger;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.component.PropUtil;

public class Server {

	private static Logger logger = Logger.getLogger(Server.class.getName());
	public static NioSocketAcceptor socketAcceptor;
	
	public Server() {
		socketAcceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() + 1);
		socketAcceptor.setReuseAddress(true);
		socketAcceptor.getSessionConfig().setKeepAlive(true);
		socketAcceptor.setHandler(new ServerHandler());
		socketAcceptor.getFilterChain().addLast("json", new ProtocolCodecFilter(new CodecFactory()));
		socketAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf8"))));
		socketAcceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));

		socketAcceptor.getSessionConfig().setReadBufferSize(1024);// 发送缓冲
																	// 1M=1024*1024
		socketAcceptor.getSessionConfig().setReceiveBufferSize(1024);// 接收缓冲

		String tishiString = "server running!:" + new Date() + "";
		System.out.println(tishiString);
	}

	public static String getEncoding(String str) {
		String encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}

		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	public void startAcceptor() {
		socketAcceptor.getManagedSessions();
		try {
			// 端口绑定
			socketAcceptor.bind(new InetSocketAddress(Integer.parseInt(PropUtil.getProperty("port"))));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
